﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UAParser;

namespace HCMS.Extensions
{
    /// <summary>
    /// HttpRequest 扩展类
    /// </summary>
    public static class HttpRequestExt
    {
        #region GetClientIp 获取客户端 Ip
        /// <summary>
        /// 获取客户端 Ip
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetClientIp(this HttpRequest request)
        {
            string ipAddress = request.Headers["X-Forwarded-For"].FirstOrDefault() ?? "";
            if (string.IsNullOrWhiteSpace(ipAddress))
            {
                ipAddress = (request.HttpContext.Connection.RemoteIpAddress?.ToString()) ?? "";
            }
            return ipAddress;
        }
        #endregion

        #region GetReferer 获取当前请求的来源 Url
        /// <summary>
        /// 获取当前请求的来源 Url
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetReferer(this HttpRequest request)
        {
            string referer = request.Headers["Referer"].ToString("");
            return referer;
        }
        #endregion

        #region GetCurrentUrl 获取当前请求 Url
        /// <summary>
        /// 获取当前请求 Url
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetCurrentUrl(this HttpRequest request)
        {
            string currentUrl = request.GetDisplayUrl();
            return currentUrl ?? "";
        }
        #endregion

        #region GetClientInfo 获取客户端信息
        /// <summary>
        /// 获取客户端信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ClientInfo? GetClientInfo(this HttpRequest request)
        {
            string userAgent = request.Headers["User-Agent"].ToString("");

            if (string.IsNullOrWhiteSpace(userAgent)) { return null; }
            var uaParser = Parser.GetDefault();

            return uaParser.Parse(userAgent);
        }
        #endregion

        #region GetClientBrower 获取客户端浏览器信息
        /// <summary>
        /// 获取客户端浏览器信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetClientBrower(this HttpRequest request)
        {
            var clientInfo = GetClientInfo(request);
            if (clientInfo == null) { return ""; }

            var ua = clientInfo.UA;
            if (ua == null) { return ""; }

            return $"{ua.Family} {ua.Major}.{ua.Minor}.{ua.Patch}";
        }
        #endregion

        #region IsSpider 是否来自爬虫请求
        /// <summary>
        /// 是否来自爬虫请求
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsSpider(this HttpRequest request)
        {
            var clientInfo = GetClientInfo(request);
            if (clientInfo == null) { return false; }

            var device = clientInfo.Device;
            if (device == null) { return false; }

            return device.IsSpider;
        }
        #endregion

        #region GetHeaderInfo 获取请求头信息
        /// <summary>
        /// 获取请求头信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns>请求头键值对列表</returns>
        public static List<object> GetHeaderInfo(this HttpRequest request)
        {
            if (request.Headers == null || request.Headers.Count == 0) { return new List<object>(); }

            var headerInfo = new List<object>();
            foreach (var headerItem in request.Headers)
            {
                var item = new
                {
                    Key = headerItem.Key,
                    Value = headerItem.Value
                };
                headerInfo.Add(item);
            }

            return headerInfo;
        }
        #endregion

        #region GetParameter 获取请求参数
        /// <summary>
        /// 获取请求参数
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<string> GetParameter(this HttpRequest request)
        {
            string parameter = string.Empty;

            //--- GET 方式请求
            // 查询参数
            if (request.Method == "GET" && !string.IsNullOrWhiteSpace(request.QueryString.Value))
            {
                parameter = request.QueryString.Value;
            }
            //--- POST 方式请求
            else if (request.Method == "POST")
            {
                request.EnableBuffering();
                request.Body.Seek(0, SeekOrigin.Begin);

                // Body 参数
                if (request.Body.Length > 0)
                {
                    using (StreamReader stream = new StreamReader(request.Body))
                    {
                        parameter = await stream.ReadToEndAsync();
                    }
                }

                // Form 参数
                if (string.IsNullOrWhiteSpace(parameter) && request.ContentLength > 0)
                {
                    var formList = new List<string>();
                    foreach (var key in request.Form.Keys)
                    {
                        formList.Add($"{key}={request.Form[key]}");
                    }
                    parameter = string.Join("&", formList);
                }
            }

            return parameter;
        }
        #endregion
    }
}
